import { reqlogin } from "../../request/api";
import { Toast } from "antd-mobile";

//状态
const initState = {
    // 1.初始化表单数据
    user: {
        phone: "",
        password: "",
    },
    // 7.1初始化用户信息 
    // 7.7 一进来页面，如果本地存储中有数据，应该取出来给userInfo,如果没有，userInfo={}
    userInfo: sessionStorage.getItem("isLogin") ? JSON.parse(sessionStorage.getItem("isLogin")) : {}
}

//actionType
const TYPES = {
    //2.修改user的type
    LOGIN_CHANGE_USER: "LOGIN_CHANGE_USER",
    // 7.2 修改userInfo 
    LOGIN_CHANGE_USER_INFO: "LOGIN_CHANGE_USER_INFO"
}

//修改state reducer 
const reducer = (state = initState, action) => {
    // console.log(action);
    switch (action.type) {
        // 3.具体修改user {type:"LOGIN_CHANGE_USER",key:"phone",value:"111"}
        case TYPES.LOGIN_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        // 7.3  修改userInfo {type:"LOGIN_CHANGE_USER_INFO",userInfo:{id:1,token:'11}}
        case TYPES.LOGIN_CHANGE_USER_INFO:
            return {
                ...state,
                userInfo: action.userInfo
            }
        default:
            return state;
    }
}

//做逻辑和异步的acitons actionCreators
export const actions = {
    //4.修改user action
    changeUser: (key, value) => ({ type: TYPES.LOGIN_CHANGE_USER, key, value }),
    // 7.4 修改用户信息 action  {id:1,token:11}  {}
    changeUserInfo: (userInfo) => {
        // 7.6.同步到本地存储，如果userInfo有token,存，否则就删
        if (userInfo.token) {
            sessionStorage.setItem('isLogin', JSON.stringify(userInfo))
        } else {
            sessionStorage.removeItem('isLogin')
        }
        return { type: TYPES.LOGIN_CHANGE_USER_INFO, userInfo }
    },
    //6.点了登录按钮
    doLogin: (push) => {
        return (dispatch, getState) => {
            //发起登录的请求
            reqlogin(getUser(getState())).then(res => {
                if (res.data.code === 200) {
                    //登录成功
                    //弹成功
                    Toast.show({
                        content: res.data.msg
                    })
                    // 存用户信息
                    dispatch(actions.changeUserInfo(res.data.list))
                    // 跳转到首页
                    push("/index/home")
                }
            })
        }
    }

}

//导出数据 Selectors 
// 5.导出user 
export const getUser = state => state.login.user;
// 7.5导出用户信息 
export const getUserInfo = state => state.login.userInfo;


//导出reducer 
export default reducer;